package com.hht.baselibs.fragment

import android.os.Build
import android.os.Bundle
import androidx.annotation.RequiresApi
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import com.hht.baselibs.viewModel.BaseViewModel
import java.lang.reflect.ParameterizedType


/**
 * Author:chen'hu
 * Time:2023/7/31 14:01
 * Description:This is BaseFragment
 */
abstract class BaseFragment<VM : BaseViewModel, DB : ViewDataBinding> : BaseLibFragment<VM, DB>() {
    @RequiresApi(Build.VERSION_CODES.P)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        bindViewModel()
        //TODO 必须加上，不然Repository无法感知生命周期防止内存泄漏
        lifecycle.addObserver(mViewModel.getRepository())
    }

    @RequiresApi(Build.VERSION_CODES.P)
    private fun bindViewModel() {
        mViewModel = ViewModelProvider(this)[getViewModelClass()]
    }

    //动态得到具体的ViewModel名字
//    @RequiresApi(api = Build.VERSION_CODES.P)
//    private fun getViewModelClass(): Class<VM> {
//        var xClass = BaseViewModel::class.java as Class<VM>
//        val typeList = (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments
//        for (i in typeList.indices) {
//            val typeName = typeList[i].typeName
//            if (typeName.contains("viewModel")) {
//                xClass =
//                    (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[i] as Class<VM>
//                return xClass
//            }
//        }
//        return xClass
//    }

    /**
     * 动态得到具体的ViewModel名字
     */
    private fun getViewModelClass(): Class<VM> {
        val type = javaClass.genericSuperclass as ParameterizedType
        val typeArguments = type.actualTypeArguments
        if (typeArguments.size != 2) {
            throw IllegalStateException("Expected 2 type arguments, but got ${typeArguments.size}")
        }
        // 假设第一个参数是 VM 类型，第二个参数是 DB 类型
        val vmType = typeArguments[0]
        if (vmType is Class<*>) {
            @Suppress("UNCHECKED_CAST") return vmType as Class<VM>
        }
        throw IllegalStateException("VM type argument is not a Class instance")
    }

    override fun onDestroy() {
        super.onDestroy()
        lifecycle.removeObserver(mViewModel.getRepository())
    }
}